<?php

class User extends CActiveRecord
{
	
	public $username;
	public $password;
	public $repassword;
	public $email;
	public $verifyCode;
	
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{user}}';
	}
	
	public function rules()
	{
		return array(
			//必填项
			array('username, password,repassword,email,verifyCode', 'required'),
				
			array('username', 'length', 'min' => 5, 'max' => 12),

			array('password', 'length', 'min' => 5, 'max' => 12),

			//验证Email
			array('email','email'),
			//用户名和Email唯一性
			array('username,email','unique'),
			//验证码
			array('verifyCode', 'captcha', 'allowEmpty'=>!CCaptcha::checkRequirements()),
				
			array('repassword', 'compare', 'compareAttribute' => 'password'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
		);
	}
	
	/**
	 * (non-PHPdoc)
	 * @see CActiveRecord::beforeSave()
	 */
	protected function beforeSave()
	{
		if(parent::beforeSave())
		{
			if($this->isNewRecord)
			{
				$this->addtime=date('Y-m-d H:i:s');
				$this->salt = md5(rand());
				$this->password = $this->hashPassword($this->password, $this->salt);
			}
			return true;
		}
		else
			return false;
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'username' => '用户名',
			'email' => 'Email',
			'password' => '密码',
			'repassword' => '重复密码',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('salt',$this->salt,true);
		$criteria->compare('addtime',$this->addtime,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
	
	/**
	 * 验证密码
	 */
	public function validatePassword($password)
	{
		
		return $this->hashPassword($password, $this->salt)===$this->password;
		
	}
	
	/**
	 * 加密密码
	 */
	public function hashPassword($password,$salt){
		return md5($password.$salt);
	}
}